package ntd.util.frame.javacv.task;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import ntd.action.ActionManager;
import ntd.action.bo.ActionInBo;
import ntd.sys.ToolJvm;
import ntd.task.Task;
import ntd.task.bo.TaskInfo;
import ntd.tool.ToolCron;
import ntd.util.UtilCatch;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.ComVisionApi;
import ntd.util.frame.javacv.action.bo.ImgAnalysisInBo;
import ntd.util.frame.javacv.bo.CameraBO;
import ntd.util.frame.javacv.vlc.FactoryVlc;
import ntd.util.util.ToolDuration;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 机器视觉轮询分析任务
 */
public class VisionAnalysisTask implements Task {
    @Override
    public TaskInfo info() {
        return new TaskInfo("任务-机器视觉轮询分析任务", "task-vision-analysis", new VisionAnalysisTask());
    }

    
    @Override
    public void execute(Object o) {
        List<CameraBO> cameraBOS = ComVisionApi.initCameraList();
        // mn 基站号补充，从开放数据平台查询mn
        Db use = Db.use(FactoryData.dataSource("cc3ac1352b104abfb86da5c351f8f68c"));
        List<Entity> query = null;
        try {
            query = use.query("select mn, camera_code from site_device");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        Map<String, Entity> cameraCodeMap = CollStreamUtil.toIdentityMap(query, entity -> entity.getStr("camera_code"));

        for (CameraBO cameraBO : cameraBOS) {
            ThreadUtil.execAsync(() -> ToolDuration.duration(() -> {
                Entity entity = cameraCodeMap.get(cameraBO.getCode());
                if (ObjectUtil.isNotNull(entity)) {
                    cameraBO.setCameraMn(entity.getStr("mn"));
                    ActionInBo actionInBo = new ActionInBo();
                    byte[] snapshotAboutBytes = FactoryVlc.getSnapshotAboutBytes(cameraBO.initRtspUrl());
                    actionInBo.setData(Dict.parse(new ImgAnalysisInBo(cameraBO.getCameraMn(), cameraBO.getCode(), snapshotAboutBytes, cameraBO.getModeTypes())));
                    UtilCatch.tryCatchNoRes(() -> ActionManager.get("ai-vision-img-analysis").getAction().execute(actionInBo));
                }
            }, "图片分析加入队列"));
        }
    }

    public static void main(String[] args) throws Exception {

        VisionAnalysisTask visionAnalysisTask = new VisionAnalysisTask();
        visionAnalysisTask.execute(null);

        // 设置不允许退出
        ToolJvm.setNoExit();

        // 设置定时任务
//        CronUtil.schedule("30 * * * * *", (Runnable) () ->  visionAnalysisTask.execute(null));

        // 启动定时任务
        ToolCron.initTask();
    }
}
